package com.numberone.master.common.filter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import com.numberone.master.common.aes.AesUtil;
import com.numberone.master.common.menu.RespCode;
import com.numberone.master.common.utils.ResponseDo;

/**
 * 接口登录拦截器
 * 
 * @author ck
 * 
 * @date 2018年2月28日下午3:45:03
 */
public class MposValiteFilter extends AccessControlFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse,
			Object mappedValue) throws Exception {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		try {
			String encryption = request.getParameter("encryption");
			String request_time = request.getParameter("request_time");
			if(StringUtils.isBlank(encryption) || StringUtils.isBlank(request_time)){
				ResponseDo.dealWithAjaxReturn(response, RespCode.NOT_PARAM_ERROR);
				return false;
			}
			boolean verification = getAllParam(request,response);
			if(verification == false){
				return false;
			}
		} catch (Exception e) {
			ResponseDo.dealWithAjaxReturn(response, RespCode.UNKNOWN_ERROR);
			return false;
		}
		return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
		return false;
	}
	
	/**
	 * 获取所有的参数
	 * @param request
	 * @return
	 */
	public static boolean getAllParam(HttpServletRequest request,HttpServletResponse response){
		Long nowTime = System.currentTimeMillis();
		Map map = request.getParameterMap();
		Map<String,String> formMap = new HashMap<>();
		String encryption = "";
	    Set keSet = map.entrySet();  
	    for(Iterator itr = keSet.iterator();itr.hasNext();){
	        Map.Entry me = (Map.Entry)itr.next();  
	        Object ok = me.getKey();  
	        Object ov = me.getValue();  
	        String[] value = new String[1];  
	        if(ov instanceof String[]){  
	            value = (String[])ov;  
	        }else{  
	            value[0] = ov.toString();  
	        }
	        //对参数做验证
	        for(int k = 0;k < value.length;k++){
	            String param = (String) ok;
	            String values = value[k];
	            if(StringUtils.equals(param, "encryption")){
	            	encryption = values;
	            }else{
	            	if(StringUtils.equals(param, "request_time")){
	            		long requestTime = Long.valueOf(values);//接口请求时间
	            		if(nowTime + 1000 * 60 < requestTime){
	            			ResponseDo.dealWithAjaxReturn(response, RespCode.ERROR_REQUEST_ENCRYPTION);
	            			return false;
	            		}
	            		if(nowTime - requestTime > 1000 * 60){
	            			ResponseDo.dealWithAjaxReturn(response, RespCode.ERROR_REQUEST_OVER_TIME);
	            			return false;
	            		}
	            	}
	            	formMap.put(param, values);
	            }
	        }
	    }
	    //Unicode码从小到大排序（字典序）
        String paramSort = AesUtil.formatUrlMap(formMap, true, true);
        if(StringUtils.isBlank(paramSort)){
        	ResponseDo.dealWithAjaxReturn(response, RespCode.NOT_PARAM_ERROR);
			return false;
        }
        //校验加密是否正确
        String paramAes = AesUtil.aesEncrypt(paramSort);
        if(!StringUtils.equals(encryption, paramAes)){
        	ResponseDo.dealWithAjaxReturn(response, RespCode.ENCRYPTION_ERROR);
			return false;
        }
	    return true;
	}
}